import router, { asyncRoutes } from './router'
import store from './store'
// 路由导航守卫

// 白名单
const whiteList = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children?.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 如果有token且不是登录页，判断是否获取过用户信息
      if (!store.getters.userId) {
        // 1. 获取原始权限列表
        const perms = await store.dispatch('user/getUserInfo')
        if (perms.length === 1 && perms[0] === '*:*:*') {
          asyncRoutes.forEach(route => router.addRoute(route))
          store.commit('user/setMenuList', asyncRoutes)
          next(to.path)
        } else {
          // 将后端数据处理成路由需要的格式
          const firstRoutePerms = getFirstRoutePerms(perms)
          const secondRoutePerms = getSecondRoutePerms(perms)
          // 3. 通过菜单权限过滤一级和二级得到权限菜单列表
          const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
          // console.log(filterRoutes)
          // 4. addRoute动态添加
          filterRoutes.forEach(route => router.addRoute(route))
          // 5. 存入vuex渲染左侧菜单
          store.commit('user/setMenuList', filterRoutes)
          next(to.path)
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
